package com.sk.sourcecircle.activity.login;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.dyhdyh.widget.loading.dialog.LoadingDialog;
import com.hyphenate.EMCallBack;
import com.hyphenate.chat.EMClient;
import com.sk.sourcecircle.R;
import com.sk.sourcecircle.activity.main.MainActivity;
import com.sk.sourcecircle.base.BaseActivity;
import com.sk.sourcecircle.callback.HandleDataCallBack;
import com.sk.sourcecircle.entity.UserInfo;
import com.sk.sourcecircle.utils.AppApi;
import com.sk.sourcecircle.utils.HttpAddress;
import com.sk.sourcecircle.utils.MD5;
import com.sk.sourcecircle.utils.MyUtils;
import com.sk.sourcecircle.utils.SPUtils;
import com.sk.sourcecircle.utils.SnackUtils;
import com.sk.sourcecircle.view.VerificationCodeButton;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by sk on 2018/1/8.
 */

public class WxInfoActivity extends BaseActivity implements HandleDataCallBack {

    @BindView(R.id.ed_account)
    EditText edAccount;
    @BindView(R.id.ed_password)
    EditText edPassword;
    @BindView(R.id.get_code)
    VerificationCodeButton getCode;
    @BindView(R.id.login)
    TextView login;
    private UserInfo.DataBean dataBean;
    private LoadingDialog loadingDialog;
    private String phone = "";
    private boolean isSuccess = false;
    private int type;

    @Override
    protected int getContentView() {
        return R.layout.activity_wx_info;
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        type = getIntent().getIntExtra("type", 0);
        loadingDialog = MyUtils.getLoadingDialog(mContext, false);
        dataBean = getIntent().getParcelableExtra("data");

    }

    private void loginHx(String account, String password) {
        EMClient.getInstance().login(account, password, new EMCallBack() {//回调
            @Override
            public void onSuccess() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        loadingDialog.cancelDialog();
                        Toast.makeText(mContext, "登录成功！", Toast.LENGTH_SHORT).show();
                    }
                });
                EMClient.getInstance().groupManager().loadAllGroups();
                EMClient.getInstance().chatManager().loadAllConversations();
//                Toast.makeText(mContext,"登录聊天服务器成功",Toast.LENGTH_SHORT).show();
                Log.d("loginHx", "登录聊天服务器成功！");
                if (type == 1) {
                    Intent intent = new Intent(mContext, MainActivity.class);
                    startActivity(intent);
                    finish();
                } else {
                    finish();
                }

            }

            @Override
            public void onProgress(int progress, String status) {


            }

            @Override
            public void onError(int code, String message) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        loadingDialog.cancelDialog();
                        Toast.makeText(mContext, "登录成功！", Toast.LENGTH_SHORT).show();
                    }
                });
//                Toast.makeText(mContext,"登录聊天服务器失败"+message,Toast.LENGTH_SHORT).show();
                Log.d("loginHx", "登录聊天服务器失败！");
                Log.d("loginHx", message);
                Intent intent = new Intent(mContext, MainActivity.class);
                startActivity(intent);
                finish();
            }
        });
    }

    @OnClick({R.id.get_code, R.id.login, R.id.jump})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.get_code:
                if (!TextUtils.isEmpty(edAccount.getText().toString()) && edAccount.getText().toString().startsWith("1") && edAccount.getText().toString().length() == 11) {
                    getCode.startTimer();
                    loadingDialog.show();
                    phone = edAccount.getText().toString();
                    AppApi.sendCode(edAccount.getText().toString(), 16, WxInfoActivity.this, 1, WxInfoActivity.this);
                } else {
                    SnackUtils.showError(mRootView, "请输入手机号!");
                }
                break;
            case R.id.login:
                if (!TextUtils.isEmpty(edPassword.getText().toString())) {
                    loadingDialog.show();
                    AppApi.vertifyCode(phone, edPassword.getText().toString(), WxInfoActivity.this, 3, WxInfoActivity.this);
                } else {
                    SnackUtils.showError(mRootView, "请输入验证码!");
                }
                break;
            case R.id.jump:
                isSuccess = true;
                loadingDialog.show();
                loginHx(dataBean.getHx_login(), dataBean.getHx_pass());
                break;
        }
    }


    public void savePhone(String phone) {
        String path = HttpAddress.TestIp + HttpAddress.SavePhone;
        RequestParams requestParams = new RequestParams(path + "/" + phone);
        long timeStamp = System.currentTimeMillis() / 1000;
        requestParams.addBodyParameter("timestamp", String.valueOf(timeStamp));
        requestParams.addBodyParameter("sign", MD5.md5(timeStamp + "_yuanquan"));
        requestParams.addBodyParameter("token", MyUtils.getToken(mContext));
//        requestParams.addBodyParameter("phone", phone);
        Log.v("requestParams", requestParams.toString());
        x.http().get(requestParams, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Log.v("savePhone", result);
                loadingDialog.cancelDialog();
                com.alibaba.fastjson.JSONObject jsonObject = JSON.parseObject(result);
                int code = jsonObject.getIntValue("code");
                if (code == 200) {
                    isSuccess = true;
                    loginHx(dataBean.getHx_login(), dataBean.getHx_pass());
                } else {
                    SnackUtils.showError(mRootView, "手机号已被绑定！");
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Log.v("savePhone", ex.toString());
                loadingDialog.cancelDialog();
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }


    @Override
    public void handlerSuccessData(String result, int tag) {
        switch (tag) {
            case 1:
                loadingDialog.cancelDialog();
                SnackUtils.show(mRootView, "验证码发送成功！");
                break;
            case 3:
                savePhone(phone);
                break;
        }
    }

    @Override
    public void handlerFailData(String failString, int tag) {
        loadingDialog.cancelDialog();
    }

    @Override
    public void handleErrorData(String error, int tag) {
        loadingDialog.cancelDialog();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (!isSuccess) {
            SPUtils.clear(mContext);
        }
    }
}
